package cz.cvut.fit.sin.eventlocator.controller;

import java.util.List;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import cz.cvut.fit.sin.eventlocator.core.EventLocator;
import cz.cvut.fit.sin.eventlocator.data.Event;
import cz.cvut.fit.sin.eventlocator.form.SearchBean;

/**
 * Main requests dispatcher
 *
 */
@Controller
@RequestMapping(value = { "", "main" })
public class EventLocatorController {
	
	@Autowired
	private EventLocator eventLocator;
	
	@RequestMapping(method = RequestMethod.GET)
	public String showPage(Model model) {
		model.addAttribute("searchBean", new SearchBean());
		return "main";
	}
	
	@RequestMapping(method = RequestMethod.POST)
	public String processSubmit(Model model, @ModelAttribute("searchBean") @Valid SearchBean form, BindingResult result) throws Exception {
		if (!result.hasErrors()) {
			List<Event> events = eventLocator.getEvents(form.getAddress());
			model.addAttribute("events", events.isEmpty() ? null : events);
			model.addAttribute("eventsCount", events.size());
		}
		return "main";
	}


}
